package com.edu.whty.controller;

import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.*;
import com.edu.whty.domain.ClassDto;
import com.edu.whty.domain.UserClassSubjectDto;
import com.edu.whty.entity.base.Pagination;
import com.edu.whty.entity.capacity.*;
import com.edu.whty.entity.disk.ChartDataDto;
import com.edu.whty.entity.disk.DiskGrowthTrend;
import com.edu.whty.entity.disk.DiskOwner;
import com.edu.whty.entity.school.GradeSubjectDto;
import com.edu.whty.entity.school.SchoolResDto;
import com.edu.whty.entity.school.SchoolResQuery;
import com.edu.whty.entity.school.TeacherResNumDto;
import com.edu.whty.service.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

/**
 * TODO
 *
 * @author hefeng
 * @explain
 * @date 2023/5/30
 */
@Slf4j
@Controller
@Component
@RequestMapping("/capacity")
public class DiskCapacityController {

    @Autowired
    private DiskService diskService;

    @Autowired
    private DiskCapacityService diskCapacityService;

    @Autowired
    private SchoolResourceService schoolResourceService;

    @Autowired
    private OpenUtil openUtil;

    /**
     * 初始化学校的网盘容量，如果已存在，则更新
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initOrgCapacity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage initOrgCapacity(@RequestBody CapacityRequest obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(obj.getOwnerId()) || obj.getMaxCapacity() == null) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("学校id和总容量不能为空");
            return responseMessage;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date());

        //如果该学校已经初始化过，更新最新容量，没有就插入一条数据
        Capacity capacity = new Capacity();
        capacity.setOwnerId(obj.getOwnerId());
        List<Capacity> capacityList = diskCapacityService.selectList(capacity);
        if (CollectionUtils.isEmpty(capacityList)) {
            capacity.setCapacityId(UUIDUtils.getRandomUUID());
            capacity.setDiskType(1);//机构
            capacity.setOrgId(obj.getOrgId());
            capacity.setOrgName(obj.getOrgName());
            //前端传过来的单位是G
            capacity.setMaxCapacity(obj.getMaxCapacity() * 1073741824);
            capacity.setUsedCapacity(0L);
            capacity.setUsedRate(0f);
            capacity.setCreateTime(dateStr);
            diskCapacityService.insertOne(capacity);
        } else {
            //更新的话，还要重新计算已使用容量和使用率
            capacity = capacityList.get(0);
            capacity.setMaxCapacity(obj.getMaxCapacity() * 1073741824);
            capacity.setModifyTime(dateStr);
            diskCapacityService.updateOne(capacity);

            //更新使用容量和使用率
            diskCapacityService.updateOrgUsed(obj.getOwnerId());
        }

        return responseMessage;
    }

    /**
     * 批量设置用户的网盘容量，如果用户的已存在，则更新
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initUserCapacity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage initUserCapacity(@RequestBody CapacityRequest obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        List<UserCapacity> userCapacityList = obj.getUserCapacityList();
        if (CollectionUtils.isEmpty(userCapacityList)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("用户列表不能为空");
            return responseMessage;
        }

        if (StringUtils.isBlank(obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("学校id不能为空");
            return responseMessage;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date());
        List<String> ownerIdList = userCapacityList.stream().map(serCapacity -> serCapacity.getOwnerId()).collect(Collectors.toList());

        Capacity capacity = new Capacity();
        capacity.setOrgId(obj.getOrgId());
        capacity.setOwnerIdList(ownerIdList);
        capacity.setDiskType(0);//用户
        List<Capacity> capacityList = diskCapacityService.selectList(capacity);

        Map<String, Capacity> userMap = new HashMap<>();
        //存在的用户更新容量及使用率，不存在的用户插入
        if (!CollectionUtils.isEmpty(capacityList)) {
            userMap = capacityList.stream().collect(Collectors.toMap(Capacity::getOwnerId, v -> v, (k1, k2) -> k2));
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("orgId", obj.getOrgId());

        //先全部查出来
        Pagination pagination = new Pagination();
        pagination.setNumPerPage(10000);
        pagination.setCurPage(1);

        //已使用的容量
        PageInfo pageInfo = diskService.selectUserCapacityListInPage(map, pagination);
        List<CapacityUsed> userCapaList = pageInfo.getList();
        Map<String, CapacityUsed> userCapaMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userCapaList)) {
            userCapaMap = userCapaList.stream().collect(Collectors.toMap(CapacityUsed::getUserId, v -> v, (k1, k2) -> k2));
        }

        //需要插入的用户
        List<Capacity> insertList = new ArrayList<>();
        //更新的用户
        List<Capacity> updateList = new ArrayList<>();
        for (int i = 0; i < userCapacityList.size(); i++) {
            UserCapacity userCapacity = userCapacityList.get(i);

            //还要判断用户已使用容量要小于新设置容量，不然不能设置
            //已使用的容量
            if (userCapaMap.get(userCapacity.getOwnerId()) != null) {
                Long usedCapacity = Long.valueOf(userCapaMap.get(userCapacity.getOwnerId()).getUsedCapacity());
                if (usedCapacity > userCapacity.getMaxCapacity() * 1073741824) {
                    responseMessage.setResult("100000");
                    responseMessage.setResultDesc("用户" + userCapacity.getRealName() + "已使用" + formatFileSize(usedCapacity) + "容量，新设置容量不能小于已使用容量");
                    return responseMessage;
                }
            }

            //已存在
            if (userMap.containsKey(userCapacity.getOwnerId())) {

                Capacity capacityUpdate = userMap.get(userCapacity.getOwnerId());
                //前端传过来的单位是G
                capacityUpdate.setMaxCapacity(userCapacity.getMaxCapacity() * 1073741824);
                capacityUpdate.setModifyTime(dateStr);
                updateList.add(capacityUpdate);
            } else {
                //不存在
                Capacity capacityInsert = new Capacity();
                capacityInsert.setCapacityId(UUIDUtils.getRandomUUID());
                capacityInsert.setDiskType(0);//用户
                capacityInsert.setOrgId(obj.getOrgId());
                capacityInsert.setOrgName(obj.getOrgName());
                //前端传过来的单位是G
                capacityInsert.setMaxCapacity(userCapacity.getMaxCapacity() * 1073741824);
                capacityInsert.setUsedCapacity(0L);
                capacityInsert.setUsedRate(0f);
                capacityInsert.setCreateTime(dateStr);
                capacityInsert.setOwnerId(userCapacity.getOwnerId());
                capacityInsert.setOwnerName(userCapacity.getOwnerName());
                capacityInsert.setRealName(userCapacity.getRealName());
                capacityInsert.setPlatformCode(obj.getPlatformCode());
                insertList.add(capacityInsert);
            }

            //用于计算老师总容量大小与学校容量大小的关系
            CapacityUsed capacityUsed = new CapacityUsed();
            capacityUsed.setUserId(userCapacity.getOwnerId());
            capacityUsed.setMaxCapacityLong(userCapacity.getMaxCapacity() * 1073741824);
            capacityUsed.setMaxCapacity(userCapacity.getMaxCapacity() * 1073741824 + "");
            userCapaMap.put(userCapacity.getOwnerId(), capacityUsed);

        }

        //计算老师总容量大小与学校容量大小的关系
        Long userCap = 0L;
        Set<Map.Entry<String, CapacityUsed>> entries = userCapaMap.entrySet();
        for (Map.Entry<String, CapacityUsed> entry : entries) {
            CapacityUsed capacityUsed = entry.getValue();
            userCap += Long.valueOf(capacityUsed.getMaxCapacity());
        }

        //查询学校的容量
        Capacity schoolCap = new Capacity();
        schoolCap.setOwnerId(obj.getOrgId());
        List<Capacity> schoolCapList = diskCapacityService.selectList(schoolCap);
        if (CollectionUtils.isEmpty(schoolCapList)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("学校未设置学校容量大小");
            return responseMessage;
        }
        if (userCap > schoolCapList.get(0).getMaxCapacity()) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("用户总容量不能大于学校总容量");
            return responseMessage;
        }

        if (!CollectionUtils.isEmpty(insertList)) {
            diskCapacityService.insertBatch(insertList);
        }

        if (!CollectionUtils.isEmpty(updateList)) {
            diskCapacityService.updateBatch(updateList);
            //再批量修改使用率
            List<String> userIdList = updateList.stream().map(capacity1 -> capacity1.getOwnerId()).collect(Collectors.toList());
            diskCapacityService.updateUsedBatch(userIdList);
        }

        return responseMessage;
    }

    /**
     * 查看学校总体容量及已使用容量
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getOrgCapacity/{orgId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getOrgCapacity(@PathVariable String orgId) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(orgId)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数orgId不能为空");
            return responseMessage;
        }
        //查询设置的学校的容量
        Capacity capacity = new Capacity();
        capacity.setOwnerId(orgId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);

        //个人网盘已使用的容量
        Long usedCapacity = diskService.getOrgCapacity(orgId);
        usedCapacity = usedCapacity == null ? 0 : usedCapacity;

        //校本资源已使用的容量
        Long usedSchoolCapacity = schoolResourceService.getSchoolCapacity(orgId);
        usedSchoolCapacity = usedSchoolCapacity == null ? 0 : usedSchoolCapacity;

        CapacityUsed capacityUsed = new CapacityUsed();
        capacityUsed.setUserId(orgId);
        Long maxCapacity = 0L;
        if (CollectionUtils.isEmpty(capaList)) {
            capacityUsed.setMaxCapacity("0B");
            capacityUsed.setMaxCapacityLong(0L);
        } else {
            maxCapacity = capaList.get(0).getMaxCapacity();
            capacityUsed.setMaxCapacity(formatFileSize(maxCapacity));
            capacityUsed.setMaxCapacityLong(maxCapacity);
        }
        capacityUsed.setUsedCapacityLong(usedCapacity + Long.valueOf(usedSchoolCapacity));
        capacityUsed.setUsedCapacity(formatFileSize(usedCapacity + Long.valueOf(usedSchoolCapacity)));

        capacityUsed.setUsageRate(getPercentage(usedCapacity + Long.valueOf(usedSchoolCapacity), maxCapacity));

        return ResponseMessage.getSuccessResponse(capacityUsed);
    }

    /**
     * 查看用户总体容量及已使用容量
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUserCapacity/{orgId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getUserCapacity(@PathVariable String orgId) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(orgId)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数orgId不能为空");
            return responseMessage;
        }

        //已分配给老师的总容量
        Long teachersCapacity = diskCapacityService.selectTeachersCapacity(orgId);
        teachersCapacity = teachersCapacity == null ? 0L : teachersCapacity;

        //个人网盘已使用的容量
        Long usedCapacity = diskService.getOrgCapacity(orgId);
        usedCapacity = usedCapacity == null ? 0 : usedCapacity;

        CapacityUsed capacityUsed = new CapacityUsed();
        capacityUsed.setUserId(orgId);
        capacityUsed.setMaxCapacity(formatFileSize(teachersCapacity));
        capacityUsed.setMaxCapacityLong(teachersCapacity);
        capacityUsed.setUsedCapacity(formatFileSize(usedCapacity));
        capacityUsed.setUsedCapacityLong(usedCapacity);
        capacityUsed.setUsageRate(getPercentage(usedCapacity, teachersCapacity));

        return ResponseMessage.getSuccessResponse(capacityUsed);
    }

    /**
     * 查看单个用户总体容量及已使用容量
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSingleUserCapacity/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getSingleUserCapacity(@PathVariable String userId) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(userId)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数userId不能为空");
            return responseMessage;
        }
        //查询设置的学校的容量
        Capacity capacity = new Capacity();
        capacity.setOwnerId(userId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);

        //已使用的容量
        Long usedCapacity = diskService.getUserCapacity(userId);
        usedCapacity = usedCapacity == null ? 0L : usedCapacity;

        CapacityUsed capacityUsed = new CapacityUsed();
        capacityUsed.setUserId(userId);
        Long maxCapacity = 0L;
        if (CollectionUtils.isEmpty(capaList)) {
            capacityUsed.setMaxCapacity("15GB");
            capacityUsed.setMaxCapacityLong(16106127360L);
            capacity.setCapacityId(UUIDUtils.getRandomUUID());
            capacity.setMaxCapacity(16106127360L);
            capacity.setUsedCapacity(0L);
            capacity.setUsedRate(0f);
            capacity.setDiskType(0);
            capacity.setCreateTime(DateUtils.getCurDateTime());
            diskCapacityService.insertOne(capacity);
        } else {
            maxCapacity = capaList.get(0).getMaxCapacity();
            capacityUsed.setMaxCapacity(formatFileSize(maxCapacity));
            capacityUsed.setMaxCapacityLong(maxCapacity);

        }
        capacityUsed.setUsedCapacity(formatFileSize(usedCapacity));
        capacityUsed.setUsedCapacityLong(usedCapacity);
        capacityUsed.setUsageRate(getPercentage(usedCapacity, maxCapacity));


        return ResponseMessage.getSuccessResponse(capacityUsed);
    }

    /**
     * 获取公共空间容量
     * 公共空间=学校总空间-分配个老师的所有空间
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getOrgPublicCapacity/{orgId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getOrgPublicCapacity(@PathVariable String orgId) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(orgId)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数orgId不能为空");
            return responseMessage;
        }
        //查询设置的学校的容量
        Long schoolCapacity = 0L;
        Capacity capacity = new Capacity();
        capacity.setOwnerId(orgId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);
        if (!CollectionUtils.isEmpty(capaList)) {
            schoolCapacity = capaList.get(0).getMaxCapacity();
        }

        //已分配给老师的总容量
        Long teachersCapacity = diskCapacityService.selectTeachersCapacity(orgId);
        teachersCapacity = teachersCapacity == null ? 0L : teachersCapacity;

        //公共空间容量
        Long publicCapacity = schoolCapacity - teachersCapacity;

        //校本资源已使用的容量
        Long usedSchoolCapacity = schoolResourceService.getSchoolCapacity(orgId);
        usedSchoolCapacity = usedSchoolCapacity == null ? 0 : usedSchoolCapacity;

        CapacityUsed capacityUsed = new CapacityUsed();
        capacityUsed.setMaxCapacity(formatFileSize(publicCapacity));
        capacityUsed.setUsedCapacity(formatFileSize(usedSchoolCapacity));
        capacityUsed.setUsageRate(getPercentage(usedSchoolCapacity, publicCapacity));

        return ResponseMessage.getSuccessResponse(capacityUsed);
    }

    /**
     * 查看学校每名教师当前使用的空间
     * 排序字段：used_capacity、max_capacity、free_capacity、usage_rate
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getOrgUserCapacityList/{orgId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getOrgUserCapacityList(@PathVariable String orgId, String orderBy, String gradeName, String subjectname,String userName, Integer curPage, Integer numPerPage) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isBlank(orgId)) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数orgId不能为空");
            return responseMessage;
        }
        if (null == curPage) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数curPage不能为空");
            return responseMessage;
        }
        if (null == numPerPage) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数numPerPage不能为空");
            return responseMessage;
        }


        HashMap<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("orderby", orderBy);

        //先全部查出来，再根据年级学科筛选
        Pagination pagination = new Pagination();
        pagination.setNumPerPage(10000);
        pagination.setCurPage(1);

        //已使用的容量
        PageInfo pageInfo = diskService.selectUserCapacityListInPage(map, pagination);
        List<CapacityUsed> capaListReturn = pageInfo.getList();
        Map<String, CapacityUsed> userMap = capaListReturn.stream().collect(Collectors.toMap(CapacityUsed::getUserId, v -> v, (k1, k2) -> k2));

        //查询用户的任教班级和学科
        List<UserClassSubjectDto> userSubjectList = openUtil.querySchoolTeacherSubject(1, orgId);

        //设置的用户容量
        List<String> ownerIdList = userSubjectList.stream().map(serCapacity -> serCapacity.getUserId()).collect(Collectors.toList());
        Capacity capacity = new Capacity();
        capacity.setOrgId(orgId);
        capacity.setOwnerIdList(ownerIdList);
        capacity.setDiskType(0);//用户
        List<Capacity> capacityList = diskCapacityService.selectList(capacity);

        Map<String, Capacity> userSetMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(capacityList)) {
            userSetMap = capacityList.stream().collect(Collectors.toMap(Capacity::getOwnerId, v -> v, (k1, k2) -> k2));
        }

        List<CapacityUsed> finalCapaListReturn = capaListReturn;
        if (!CollectionUtils.isEmpty(userSubjectList)) {

            Map<String, Capacity> finalUserSetMap = userSetMap;
            userSubjectList.forEach(userClassSubjectDto -> {

                //实际使用的容量
                CapacityUsed capacityUsed = userMap.get(userClassSubjectDto.getUserId());
                //管理员设置的容量，上面capacityUsed其实有大部分的设置容量，只是如果老师完全没有上传过文件，上面方法查不到
                Capacity setCapacity = finalUserSetMap.get(userClassSubjectDto.getUserId());

                if (capacityUsed != null) {
                    Long maxCapacity = Long.valueOf(capacityUsed.getMaxCapacity());
                    Long usedCapacity = Long.valueOf(capacityUsed.getUsedCapacity());

                    capacityUsed.setUsedCapacityLong(usedCapacity);
                    capacityUsed.setMaxCapacity(formatFileSize(maxCapacity));
                    capacityUsed.setMaxCapacityLong(maxCapacity);
                    capacityUsed.setUsedCapacity(formatFileSize(usedCapacity));
                    capacityUsed.setFreeCapacity(formatFileSize(maxCapacity - usedCapacity));
                    capacityUsed.setUsageRate(getPercentage(usedCapacity, maxCapacity));
                } else {
                    capacityUsed = new CapacityUsed();
                    capacityUsed.setUserId(userClassSubjectDto.getUserId());
                    capacityUsed.setUserName(userClassSubjectDto.getName());
                    capacityUsed.setUsedCapacityLong(0L);
                    capacityUsed.setMaxCapacity(setCapacity == null ? "0B" : formatFileSize(setCapacity.getMaxCapacity()));
                    capacityUsed.setMaxCapacityLong(setCapacity == null ? 0 : setCapacity.getMaxCapacity());
                    capacityUsed.setUsedCapacity("0B");
                    capacityUsed.setFreeCapacity(setCapacity == null ? "0B" : formatFileSize(setCapacity.getMaxCapacity()));
                    capacityUsed.setUsageRate("0%");
                    finalCapaListReturn.add(capacityUsed);
                }
            });
        }

        if (!CollectionUtils.isEmpty(userSubjectList) && !CollectionUtils.isEmpty(finalCapaListReturn)) {
            Map<String, UserClassSubjectDto> usermap = userSubjectList.stream().collect(Collectors.toMap(UserClassSubjectDto::getUserId, v -> v, (k1, k2) -> k2));
            //遍历分页之后查询的用户，给每个用户赋值任教班级和学科
            finalCapaListReturn.forEach(capacityUsed -> {

                Set<String> gradeNameList = new HashSet<>();
                Set<String> classNameList = new HashSet<>();
                Set<String> subjectNameList = new HashSet<>();
                UserClassSubjectDto userClassSubject = usermap.get(capacityUsed.getUserId());
                if (userClassSubject != null && !CollectionUtils.isEmpty(userClassSubject.getClassList())) {
                    List<ClassDto> classList = userClassSubject.getClassList();
                    //遍历任教班级
                    classList.forEach(classDto -> {
                        if (!CollectionUtils.isEmpty(classDto.getSubjectList())) {
                            classNameList.add(classDto.getClassName());
                            if (StringUtils.isNotEmpty(classDto.getClassName()) && classDto.getClassName().contains("年级")) {
                                gradeNameList.add(classDto.getClassName().substring(0, classDto.getClassName().indexOf("年级") + 2));
                            }

                            classDto.getSubjectList().forEach(subjectDto -> {
                                subjectNameList.add(subjectDto.getSubjectName());
                            });
                        }

                    });

                }
                capacityUsed.setClassNameList(classNameList);
                capacityUsed.setSubjectNameList(subjectNameList);
                capacityUsed.setGradeNameList(gradeNameList);

                if (userClassSubject != null && StringUtils.isNotEmpty(userClassSubject.getName())) {
                    capacityUsed.setUserName(userClassSubject.getName());
                }

            });
        }

        //没有姓名的用户代表不是该学校的用户
        Iterator iterator = finalCapaListReturn.iterator();
        while (iterator.hasNext()) {
            CapacityUsed cap =(CapacityUsed) iterator.next();
            if(StringUtil.isEmpty(cap.getUserName())){
                iterator.remove();
            }
        }



        if (StringUtils.isNotEmpty(gradeName)) {
            if ("高一".equals(gradeName) || "高中一年级".equals(gradeName) || "十年级".equals(gradeName)) {
                capaListReturn = capaListReturn.stream().filter(item -> item.getGradeNameList().contains("高一") || item.getGradeNameList().contains("高中一年级") || item.getGradeNameList().contains("十年级")).collect(toList());
            } else if ("高二".equals(gradeName) || "高中二年级".equals(gradeName) || "十一年级".equals(gradeName)) {
                capaListReturn = capaListReturn.stream().filter(item -> item.getGradeNameList().contains("高二") || item.getGradeNameList().contains("高中二年级") || item.getGradeNameList().contains("十一年级")).collect(toList());
            } else if ("高三".equals(gradeName) || "高中三年级".equals(gradeName) || "十二年级".equals(gradeName)) {
                capaListReturn = capaListReturn.stream().filter(item -> item.getGradeNameList().contains("高三") || item.getGradeNameList().contains("高中三年级") || item.getGradeNameList().contains("十二年级")).collect(toList());
            } else {
                capaListReturn = capaListReturn.stream().filter(item -> item.getGradeNameList().contains(gradeName)).collect(toList());
            }

        }
        if (StringUtils.isNotEmpty(subjectname)) {
            capaListReturn = capaListReturn.stream().filter(item -> item.getSubjectNameList().contains(subjectname)).collect(toList());
        }
        if (StringUtils.isNotEmpty(userName)) {
            capaListReturn = capaListReturn.stream().filter(item -> StringUtils.isNotEmpty(item.getUserName()) && item.getUserName().contains(userName)).collect(toList());
        }

        //排序
        if(StringUtils.isNotEmpty(orderBy)){
            //按总容量排序
            if(orderBy.contains("max_capacity")){
                if(orderBy.contains("desc")){//降序
                    capaListReturn.sort(comparing(CapacityUsed::getMaxCapacityLong).reversed());
                }else {//升序
                    capaListReturn.sort(comparing(CapacityUsed::getMaxCapacityLong));
                }
            }else if(orderBy.contains("used_capacity")){//按使用容量排序
                if(orderBy.contains("desc")){//降序
                    capaListReturn.sort(comparing(CapacityUsed::getUsedCapacityLong).reversed());
                }else {//升序
                    capaListReturn.sort(comparing(CapacityUsed::getUsedCapacityLong));
                }
            }else if(orderBy.contains("usage_rate")){//按使用率排序
                if(orderBy.contains("desc")){//降序
                    capaListReturn.sort(Comparator.comparing(obj -> Double.valueOf(((CapacityUsed) obj).getUsageRate().replace("%",""))).reversed());
                }else {//升序
                    capaListReturn.sort(Comparator.comparing(obj -> Double.valueOf(((CapacityUsed) obj).getUsageRate().replace("%",""))));
                }
            }

        }


        CustomPage<CapacityUsed> photoCustomPage = new CustomPage<>(capaListReturn, curPage, numPerPage);

        return ResponseMessage.getSuccessResponse(photoCustomPage);
    }

    /**
     * 查看一体机容量变化
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCapacityChanges", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getCapacityChanges(String orgId, String userId) throws Exception {

        DiskOwner query = new DiskOwner();
        if (StringUtils.isNotEmpty(orgId)) {
            query.setOrgId(orgId);
        }
        if (StringUtils.isNotEmpty(userId)) {
            query.setUserId(userId);
        }

        //上周新增
        query.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getWeekStart(DateUtils.getNextDay(new Date(), -7))));
        query.setModifyTimeEnd(DateUtils.dateToDateString(DateUtils.getWeekEnd(DateUtils.getNextDay(new Date(), -7))));
        Long prevWeek = diskService.getCapacityByCondition(query);

        //上上周新增
        query.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getWeekStart(DateUtils.getNextDay(new Date(), -14))));
        query.setModifyTimeEnd(DateUtils.dateToDateString(DateUtils.getWeekEnd(DateUtils.getNextDay(new Date(), -14))));
        Long prev2Week = diskService.getCapacityByCondition(query);

        //上月新增
        query.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getMonthStart(DateUtils.getNextMonth(new Date(), -1))));
        query.setModifyTimeEnd(DateUtils.dateToDateString(DateUtils.getMonthEnd(DateUtils.getNextMonth(new Date(), -1))));
        Long prevMonth = diskService.getCapacityByCondition(query);

        //上上月新增
        query.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getMonthStart(DateUtils.getNextMonth(new Date(), -2))));
        query.setModifyTimeEnd(DateUtils.dateToDateString(DateUtils.getMonthEnd(DateUtils.getNextMonth(new Date(), -2))));
        Long prev2Month = diskService.getCapacityByCondition(query);

        //过去90天新增
        query.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextDay(new Date(), -90)));
        query.setModifyTimeEnd(DateUtils.dateToDateString(new Date()));
        Long last90Days = diskService.getCapacityByCondition(query);

        //把为空的全部赋值0
        prevWeek = prevWeek == null ? 0 : prevWeek;
        prev2Week = prev2Week == null ? 0 : prev2Week;
        prevMonth = prevMonth == null ? 0 : prevMonth;
        prev2Month = prev2Month == null ? 0 : prev2Month;
        last90Days = last90Days == null ? 0 : last90Days;

        Map<String, Object> map = new HashMap<>();
        map.put("prevWeek", formatFileSize(prevWeek));
        map.put("prevMonth", formatFileSize(prevMonth));

        //环比，要考虑0的情况
        if (prev2Week == 0) {
            map.put("prevWeekWOW", "0%");
        } else {
            NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            nf.setGroupingUsed(false);
            Double prevWeekWOW = (prevWeek - prev2Week) * 100.0 / prev2Week;
            map.put("prevWeekWOW", nf.format(prevWeekWOW) + "%");
        }

        if (prev2Month == 0) {
            map.put("prevMonthMOM", "0%");
        } else {
            NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            nf.setGroupingUsed(false);
            Double prevMonthMOM = (prevMonth - prev2Month) * 100.0 / prev2Month;
            map.put("prevMonthMOM", nf.format(prevMonthMOM) + "%");
        }

        //算出剩余空间

        //查询设置的学校的容量
        Capacity capacity = new Capacity();
        capacity.setOwnerId(orgId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);

        //个人网盘已使用的容量
        Long usedCapacity = diskService.getOrgCapacity(orgId);
        usedCapacity = usedCapacity == null ? 0 : usedCapacity;

        //校本资源已使用的容量
        Long usedSchoolCapacity = schoolResourceService.getSchoolCapacity(orgId);
        usedSchoolCapacity = usedSchoolCapacity == null ? 0 : usedSchoolCapacity;

        Long maxCapacity = 0L;
        if (!CollectionUtils.isEmpty(capaList)) {
            maxCapacity = capaList.get(0).getMaxCapacity();
        }
        Long freeCapacity = maxCapacity - usedCapacity - usedSchoolCapacity;
        map.put("freeCapacity", formatFileSize(freeCapacity));
        //小于10G的，都返回999999
        if (last90Days <= 10737418240L) {
            map.put("remainderDays", 999999);
        } else {
            map.put("remainderDays", freeCapacity * 90 / last90Days);
        }


        return ResponseMessage.getSuccessResponse(map);
    }

    /**
     * 计算文件大小
     *
     * @param size
     * @return
     */
    public static String formatFileSize(long size) {
        //保留1位小数
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(1);
        nf.setGroupingUsed(false);

        String fileSizeString = "";
        String wrongSize = "0B";
        if (size == 0) {
            return wrongSize;
        }
        //是否是负数
        boolean negativeFlag = false;
        if (size < 0) {
            negativeFlag = true;
            size = size * -1;
        }
        if (size < 1024) {
            fileSizeString = nf.format((double) size) + "B";
        } else if (size < 1048576) {
            fileSizeString = nf.format((double) size / 1024) + "KB";
        } else if (size < 1073741824) {
            fileSizeString = nf.format((double) size / 1048576) + "MB";
        } else if (size < 1099511627776L) {
            fileSizeString = nf.format((double) size / 1073741824) + "GB";
        } else if (size < 1125899906842624L) {
            fileSizeString = nf.format((double) size / 1099511627776L) + "TB";
        } else {
            fileSizeString = nf.format((double) size / 1125899906842624L) + "PB";
        }
        if (negativeFlag) {
            return "-" + fileSizeString;
        }
        return fileSizeString;
    }


    /**
     * 计算百分比
     *
     * @param numerator，分子
     * @param denominator，分母
     * @return
     */
    public static String getPercentage(long numerator, long denominator) {
        DecimalFormat df = new DecimalFormat("#.00");
        String retString = "0%";
        //分子=0
        if (numerator == 0) {
            return retString;
        }
        //分母=0
        if (denominator == 0) {
            return "100%";
        }
        //最大显示100%
        if (numerator >= denominator) {
            return "100%";
        }

        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(1);
        nf.setGroupingUsed(false);
        Double percentage = numerator * 100.0 / denominator;
        retString = nf.format(percentage) + "%";

        return retString;
    }

    /**
     * 大值换算成GB、TB单位
     *
     * @param dataList
     * @return
     */
    public static List<DiskGrowthTrend> getFileSizeAndUnit(List<DiskGrowthTrend> dataList) {

        //一组数据的最大值
        Long maxSize = dataList.stream().max(comparing(DiskGrowthTrend::getFileLength)).orElse(new DiskGrowthTrend()).getFileLength();
        //算出单位
        String unit = "GB";
        Long divisor = 1024L;

        if (maxSize < 1024) {
            unit = "B";
            divisor = 1L;
        } else if (maxSize < 1048576) {
            unit = "KB";
            divisor = 1024L;
        } else if (maxSize < 1073741824) {
            unit = "MB";
            divisor = 1048576L;
        } else if (maxSize < 1099511627776L) {
            unit = "GB";
            divisor = 1073741824L;
        } else if (maxSize < 1125899906842624L) {
            unit = "TB";
            divisor = 1099511627776L;
        } else {
            unit = "PB";
            divisor = 1125899906842624L;
        }

        //遍历所有数据
        for (int i = 0; i < dataList.size(); i++) {
            dataList.get(i).setUnit(unit);
            dataList.get(i).setFileLength(dataList.get(i).getFileLength() / divisor);
        }

        return dataList;
    }

    /**
     * 查看学校或教师的资源增长趋势
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDiskGrowthTrend", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getDiskGrowthTrend(String orgId, String userId) throws Exception {

        DiskOwner query = new DiskOwner();
        if (StringUtils.isNotEmpty(orgId)) {
            query.setOrgId(orgId);
        }
        if (StringUtils.isNotEmpty(userId)) {
            query.setUserId(userId);
        }

        //按天统计，这里是按时间倒序的，查出的数据补过0了，肯定大于30条的
        List<DiskGrowthTrend> daylist = diskService.getGrowthTrendByDay(query);
        //按周统计
        List<DiskGrowthTrend> weeklist = diskService.getGrowthTrendByWeek(query);
        //按半月统计
        List<DiskGrowthTrend> halfMonthlist = diskService.getGrowthTrendByHalfMonth(query);
        //按月统计
        List<DiskGrowthTrend> monthlist = diskService.getGrowthTrendByMonth(query);

        //按天统计，每2天一个点，这里合并一下，取15个点
        List<DiskGrowthTrend> day2list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            DiskGrowthTrend diskGrowthTrend = new DiskGrowthTrend();
            diskGrowthTrend.setCtime(daylist.get(i * 2).getCtime());
            diskGrowthTrend.setFileLength(daylist.get(i * 2).getFileLength() + daylist.get(i * 2 + 1).getFileLength());
            day2list.add(diskGrowthTrend);
        }

        //这里的大小全部是B，要按最大值换算成GB、TB单位
        day2list = day2list.stream().sorted(comparing(DiskGrowthTrend::getCtime)).collect(Collectors.toList());
        weeklist = weeklist.subList(0, 12).stream().sorted(comparing(DiskGrowthTrend::getCtime)).collect(Collectors.toList());
        halfMonthlist = halfMonthlist.subList(0, 12).stream().sorted(comparing(DiskGrowthTrend::getCtime)).collect(Collectors.toList());
        monthlist = monthlist.subList(0, 12).stream().sorted(comparing(DiskGrowthTrend::getCtime)).collect(Collectors.toList());

        Map<String, Object> map = new HashMap();
        //一共15个点，按时间正序
        map.put("daylist", getFileSizeAndUnit(day2list));
        //剩下的取12个点，然后按时间正序
        map.put("weeklist", getFileSizeAndUnit(weeklist));
        map.put("halfMonthlist", getFileSizeAndUnit(halfMonthlist));
        map.put("monthlist", getFileSizeAndUnit(monthlist));

        return ResponseMessage.getSuccessResponse(map);
    }

    /**
     * 校本资源的类型统计
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDataByClassification", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getDataByClassification(@RequestBody SchoolResQuery obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isAnyEmpty(obj.getDateType(), obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数dateType和orgId不能为空");
            return responseMessage;
        }

        /**
         * 时间类型，1-近30天，2-近3个月，3-近6个月，4-累计，5-自定义范围
         */
        if ("1".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -1)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("2".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -3)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("3".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -6)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("4".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(null);
            obj.setModifyTimeEnd(null);
        } else if ("5".equals(obj.getDateType())) {
            if (StringUtils.isAnyEmpty(obj.getModifyTimeBegin(), obj.getModifyTimeEnd())) {
                responseMessage.setResult("100000");
                responseMessage.setResultDesc("参数modifyTimeBegin和modifyTimeEnd不能为空");
                return responseMessage;
            }
        }

        List<ChartDataDto> datalist = schoolResourceService.getSchoolResClassification(obj);

        return ResponseMessage.getSuccessResponse(datalist);
    }

    /**
     * 按资源格式分布
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDataByExt", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getDataByExt(@RequestBody SchoolResQuery obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isAnyEmpty(obj.getDateType(), obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数dateType和orgId不能为空");
            return responseMessage;
        }

        /**
         * 时间类型，1-近30天，2-近3个月，3-近6个月，4-累计，5-自定义范围
         */
        if ("1".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -1)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("2".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -3)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("3".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -6)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("4".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(null);
            obj.setModifyTimeEnd(null);
        } else if ("5".equals(obj.getDateType())) {
            if (StringUtils.isAnyEmpty(obj.getModifyTimeBegin(), obj.getModifyTimeEnd())) {
                responseMessage.setResult("100000");
                responseMessage.setResultDesc("参数modifyTimeBegin和modifyTimeEnd不能为空");
                return responseMessage;
            }
        }

        List<ChartDataDto> datalist = schoolResourceService.getSchoolResExt(obj);
        Map<String, Integer> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(datalist)) {
            datalist.forEach(data -> {
                String fileExt = data.getKeyStr();
                if (StringUtils.isNotBlank(fileExt)) {
                    if (Constant.ioc_doc.contains(fileExt) || "wps".equals(fileExt)) {
                        sumExtNum(map, "文档", data.getValueStr());
                    } else if (Constant.ioc_pdf.contains(fileExt)) {
                        sumExtNum(map, "文档", data.getValueStr());
                    } else if (Constant.ioc_html.contains(fileExt)) {
                        sumExtNum(map, "文档", data.getValueStr());
                    } else if (Constant.ioc_ppt.contains(fileExt)) {
                        sumExtNum(map, "文档", data.getValueStr());
                    } else if (Constant.ioc_image.contains(fileExt)) {
                        sumExtNum(map, "图片", data.getValueStr());
                    } else if (Constant.ioc_movie.contains(fileExt)) {
                        sumExtNum(map, "视频", data.getValueStr());
                    } else if (Constant.ioc_xls.contains(fileExt)) {
                        sumExtNum(map, "表格", data.getValueStr());
                    } else if (Constant.ioc_txt.contains(fileExt)) {
                        sumExtNum(map, "文档", data.getValueStr());
                    } else if (Constant.ioc_music.contains(fileExt)) {
                        sumExtNum(map, "音频", data.getValueStr());
                    } else {
                        sumExtNum(map, "其他", data.getValueStr());
                    }
                } else {
                    sumExtNum(map, "其他", data.getValueStr());
                }
            });
        }

        List<ChartDataDto> result = map.entrySet().stream().map(c -> new ChartDataDto(c.getKey(), c.getValue())).collect(Collectors.toList());

        return ResponseMessage.getSuccessResponse(result);
    }

    //存在则相加，不存在则设置
    private Map<String, Integer> sumExtNum(Map<String, Integer> map, String key, Integer num) {

        if (StringUtil.isEmpty(key)) {
            key = "其他";
        }

        if (map.containsKey(key)) {
            map.put(key, map.get(key) + num);
        } else {
            map.put(key, num);
        }

        return map;
    }

    /**
     * 同步、专题资源统计
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDataByRepo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getDataByRepo(@RequestBody SchoolResQuery obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isAnyEmpty(obj.getDateType(), obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数dateType和orgId不能为空");
            return responseMessage;
        }

        /**
         * 时间类型，1-近30天，2-近3个月，3-近6个月，4-累计，5-自定义范围
         */
        if ("1".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -1)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("2".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -3)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("3".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -6)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("4".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(null);
            obj.setModifyTimeEnd(null);
        } else if ("5".equals(obj.getDateType())) {
            if (StringUtils.isAnyEmpty(obj.getModifyTimeBegin(), obj.getModifyTimeEnd())) {
                responseMessage.setResult("100000");
                responseMessage.setResultDesc("参数modifyTimeBegin和modifyTimeEnd不能为空");
                return responseMessage;
            }
        }

        List<ChartDataDto> datalist = schoolResourceService.getSchoolResRepo(obj);
        Map<String, Integer> map = new HashMap<>();
        map.put("专题资源", 0);
        map.put("同步资源", 0);
        map.put("资源总数", 0);
        if (!CollectionUtils.isEmpty(datalist)) {
            datalist.forEach(data -> {
                if ("专题资源".equals(data.getKeyStr())) {
                    map.put("专题资源", data.getValueStr());
                } else if ("同步资源".equals(data.getKeyStr())) {
                    map.put("同步资源", data.getValueStr());
                }
            });
            map.put("资源总数", map.get("专题资源") + map.get("同步资源"));
        }

        return ResponseMessage.getSuccessResponse(map);
    }

    /**
     * 按老师统计资源数
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDataByTeacher", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getDataByTeacher(@RequestBody SchoolResQuery obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isAnyEmpty(obj.getDateType(), obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数dateType和orgId不能为空");
            return responseMessage;
        }

        /**
         * 时间类型，1-近30天，2-近3个月，3-近6个月，4-累计，5-自定义范围
         */
        if ("1".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -1)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("2".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -3)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("3".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -6)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("4".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(null);
            obj.setModifyTimeEnd(null);
        } else if ("5".equals(obj.getDateType())) {
            if (StringUtils.isAnyEmpty(obj.getModifyTimeBegin(), obj.getModifyTimeEnd())) {
                responseMessage.setResult("100000");
                responseMessage.setResultDesc("参数modifyTimeBegin和modifyTimeEnd不能为空");
                return responseMessage;
            }
        }

        Pagination pagination = new Pagination();
        pagination.setNumPerPage(obj.getNumPerPage() == null ? 20 : obj.getNumPerPage());
        pagination.setCurPage(obj.getCurPage() == null ? 1 : obj.getCurPage());

        PageInfo pageInfo = schoolResourceService.getSchoolResTeacher(pagination, obj);

        return ResponseMessage.getSuccessResponse(pageInfo);
    }


    @RequestMapping(value = "/excelDataByTeacher", method = RequestMethod.GET)
    public void excelDataByTeacher(HttpServletResponse response, String orgId) throws Exception {

        SchoolResQuery obj = new SchoolResQuery();
        obj.setOrgId(orgId);
        obj.setModifyTimeBegin(null);
        obj.setModifyTimeEnd(null);

        Pagination pagination = new Pagination();
        pagination.setNumPerPage(10000);
        pagination.setCurPage(1);

        PageInfo pageInfo = schoolResourceService.getSchoolResTeacher(pagination, obj);

        List<TeacherResNumDto> dataList = pageInfo.getList();
        ExcelUtil.writeExcel(response, "教师贡献排名", dataList, TeacherResNumDto.class);

    }


    @RequestMapping(value = "/excelDataByTeacherJson", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage excelDataByTeacherJson(HttpServletResponse response, String orgId) throws Exception {
        SchoolResQuery obj = new SchoolResQuery();
        obj.setOrgId(orgId);
        obj.setModifyTimeBegin(null);
        obj.setModifyTimeEnd(null);
        Pagination pagination = new Pagination();
        pagination.setNumPerPage(10000);
        pagination.setCurPage(1);
        PageInfo pageInfo = schoolResourceService.getSchoolResTeacher(pagination, obj);
        List<TeacherResNumDto> dataList = pageInfo.getList();
        return ResponseMessage.getSuccessResponse(dataList);
    }



    /**
     * 按年级学科分布
     *
     * @param obj
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDataByGrade", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getDataByGrade(@RequestBody SchoolResQuery obj) throws Exception {
        ResponseMessage responseMessage = ResponseMessage.getSuccessResponse();

        if (StringUtils.isAnyEmpty(obj.getDateType(), obj.getOrgId())) {
            responseMessage.setResult("100000");
            responseMessage.setResultDesc("参数dateType和orgId不能为空");
            return responseMessage;
        }

        /**
         * 时间类型，1-近30天，2-近3个月，3-近6个月，4-累计，5-自定义范围
         */
        if ("1".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -1)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("2".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -3)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("3".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(DateUtils.dateToDateString(DateUtils.getNextMonth(new Date(), -6)));
            obj.setModifyTimeEnd(DateUtils.getCurDateTime());
        } else if ("4".equals(obj.getDateType())) {
            obj.setModifyTimeBegin(null);
            obj.setModifyTimeEnd(null);
        } else if ("5".equals(obj.getDateType())) {
            if (StringUtils.isAnyEmpty(obj.getModifyTimeBegin(), obj.getModifyTimeEnd())) {
                responseMessage.setResult("100000");
                responseMessage.setResultDesc("参数modifyTimeBegin和modifyTimeEnd不能为空");
                return responseMessage;
            }
        }

        List<GradeSubjectDto> gradeList = schoolResourceService.getSchoolResGrade(obj);

        return ResponseMessage.getSuccessResponse(gradeList);
    }

    /**
     * 校本资源应用分析
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSchoolResCount", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getSchoolResCount() throws Exception {

        //按天统计，这里是按时间倒序的，查出的数据补过0了，肯定大于30条的
        List<SchoolResDto> daylist = schoolResourceService.getSchoolResByDay();
        //按周统计
        List<SchoolResDto> weeklist = schoolResourceService.getSchoolResByWeek();
        //按半月统计
        List<SchoolResDto> halfMonthlist = schoolResourceService.getSchoolResByHalfMonth();
        //按月统计
        List<SchoolResDto> monthlist = schoolResourceService.getSchoolResByMonth();

        //按天统计，每2天一个点，这里合并一下，取15个点
        List<SchoolResDto> day2list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            SchoolResDto schoolResDto = new SchoolResDto();
            schoolResDto.setCtime(daylist.get(i * 2).getCtime());
            schoolResDto.setDownCount(daylist.get(i * 2).getDownCount() + daylist.get(i * 2 + 1).getDownCount());
            schoolResDto.setJoinCount(daylist.get(i * 2).getJoinCount() + daylist.get(i * 2 + 1).getJoinCount());
            schoolResDto.setOpenCount(daylist.get(i * 2).getOpenCount() + daylist.get(i * 2 + 1).getOpenCount());
            schoolResDto.setViewCount(daylist.get(i * 2).getViewCount() + daylist.get(i * 2 + 1).getViewCount());
            day2list.add(schoolResDto);
        }

        Map<String, Object> map = new HashMap();
        //一共15个点，按时间正序
        map.put("daylist", day2list.stream().sorted(comparing(SchoolResDto::getCtime)).collect(Collectors.toList()));
        //剩下的取12个点，然后按时间正序
        map.put("weeklist", weeklist.subList(0, 12).stream().sorted(comparing(SchoolResDto::getCtime)).collect(Collectors.toList()));
        map.put("halfMonthlist", halfMonthlist.subList(0, 12).stream().sorted(comparing(SchoolResDto::getCtime)).collect(Collectors.toList()));
        map.put("monthlist", monthlist.subList(0, 12).stream().sorted(comparing(SchoolResDto::getCtime)).collect(Collectors.toList()));

        return ResponseMessage.getSuccessResponse(map);
    }

    /**
     * 获取学校年级，因为是单个学校独立部署的，就不去平台查了，直接初始化在自己的表里算了
     * 根据学段联动
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSchoolGradeList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getSchoolGradeList(String periodId) throws Exception {

        List<GradeInfo> gradeList = schoolResourceService.listSchoolGrade(periodId);

        return ResponseMessage.getSuccessResponse(gradeList);
    }

    /**
     * 获取学校学科，因为是单个学校独立部署的，就不去平台查了，直接初始化在自己的表里算了
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSchoolSubjectList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getSchoolSubjectList() throws Exception {

        List<SubjectInfo> subjectList = schoolResourceService.listSchoolSubject();

        return ResponseMessage.getSuccessResponse(subjectList);
    }

    /**
     * 获取学校学段，因为是单个学校独立部署的，就不去平台查了，直接初始化在自己的表里算了
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSchoolPeriodList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseMessage getSchoolPeriodList() throws Exception {

        List<PeriodInfo> periodList = schoolResourceService.listSchoolPeriod();

        return ResponseMessage.getSuccessResponse(periodList);
    }


    /**
     * 计算网盘容量（判断能否上传）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/caclCapacity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage caclCapacity(@RequestBody JSONObject obj) throws Exception {
        ResponseMessage rm = ResponseMessage.getSuccessResponse();
        String userId = obj.optString("userId");
        Long fileLength = obj.getLong("fileLength");
        //String updateType = obj.optString("updateType");
        if (StringUtils.isBlank(userId)) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("用户id不能为空");
            return rm;
        }
        if (fileLength == null) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("文件大小不能为空");
            return rm;
        }

        Capacity capacity = new Capacity();
        capacity.setOwnerId(userId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);
        if (capaList.isEmpty()) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("校园主机网盘不存在，请联系管理员创建");
            return rm;
        } else {
            capacity = capaList.get(0);
            Long usedCapacity = capacity.getUsedCapacity() == null ? 0 : capacity.getUsedCapacity();
            if (usedCapacity + fileLength > capacity.getMaxCapacity()) {
                rm = ResponseMessage.getFailedResponse();
                rm.setResultDesc("校园主机网盘容量不足，请联系管理员扩容");
                return rm;
            }
        }
        return rm;
    }


    /**
     * 修改网盘容量
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateCapacity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseMessage updateCapacity(@RequestBody JSONObject obj) throws Exception {
        ResponseMessage rm = ResponseMessage.getSuccessResponse();
        String userId = obj.optString("userId");
        Long fileLength = obj.getLong("fileLength");
        String updateType = obj.optString("updateType");
        if (StringUtils.isBlank(userId)) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("用户id不能为空");
            return rm;
        }
        if (fileLength == null) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("文件大小不能为空");
            return rm;
        }

        Capacity capacity = new Capacity();
        capacity.setOwnerId(userId);
        List<Capacity> capaList = diskCapacityService.selectList(capacity);
        if (capaList.isEmpty()) {
            rm = ResponseMessage.getFailedResponse();
            rm.setResultDesc("校园主机网盘不存在，请联系管理员创建");
            return rm;
        } else {
            capacity = capaList.get(0);
            diskCapacityService.updateDiskCapacity(capacity, fileLength, updateType);
            ;
            return rm;
        }

    }

}
